package com.yasha.sharingnews;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.TypedArray;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.agimind.widget.SlideHolder;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.yasha.adapter.ListChuyenMucAdapter;
import com.yasha.control.NewsController;
import com.yasha.customview.UserController;
import com.yasha.model.News;
import com.yasha.ulti.Tools;

public class MainPageActivty extends SherlockActivity implements
		OnMapLongClickListener, OnMarkerClickListener {

	private String TAG = "MainPageActivity";
	private GoogleMap map;
	public static String IDString = "";

	private ProgressDialog ringProgressDialog;
	private SlideHolder sildingLayout;

	private ActionBar actionBar;
	private Bundle extras;

	private NewsController newsController;
	private Spinner spn_topic_search, spn_city_search;
	private EditText txt_search;
	private Button btn_search;
	private ImageView btn_current_location;
	
	RadioGroup radioLangGroup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		newsController = new NewsController();
		if (Tools.getConnectivityStatus(this) == Tools.TYPE_NOT_CONNECTED) {
			ShowConnectErrorDialog(R.string.connect_error_title,
					R.string.no_internet_access);
		} else {

			IDString = Tools.loadSavedPreferences(this,
					Tools.sharePreferencesUserKey, Tools.UserIDkey);
			String Username = Tools.loadSavedPreferences(this,
					Tools.sharePreferencesUserKey, Tools.UserEmailkey);
			String Phone = Tools.loadSavedPreferences(this,
					Tools.sharePreferencesUserKey, Tools.UserPhonekey);

			extras = getIntent().getExtras();
			if (IDString.equals("") && extras != null && Username.equals("")
					&& Phone.equals("")) {
				// Send Request get IDString

				ringProgressDialog = ProgressDialog.show(MainPageActivty.this,
						null, null);
				ringProgressDialog.setCancelable(false);

				createUserIDString();
			} else {
				createActionBarViewAndSlidingMenu();
				showUI();
			}
		}
	}

	private void createUserIDString() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				UserController userCL = new UserController();
				final String username = extras.getString("username");
				final String phone = extras.getString("phone");
				if (!username.equals("") && !phone.equals("")) {
					IDString = userCL.addUserToServer(username, phone);
				}
				runOnUiThread(new Runnable() {

					@Override
					public void run() {

						if (ringProgressDialog.isShowing()
								&& ringProgressDialog != null) {
							ringProgressDialog.dismiss();
							ringProgressDialog = null;
						}
						if (IDString.equals("")) {
							ShowConnectErrorDialog(
									R.string.request_error_title,
									R.string.request_add_user_error);
						} else {
							boolean saveDataResult = Tools.savePreferences(
									MainPageActivty.this,
									Tools.sharePreferencesUserKey,
									Tools.UserIDkey, IDString);
							boolean saveUsername = Tools.savePreferences(
									MainPageActivty.this,
									Tools.sharePreferencesUserKey,
									Tools.UserEmailkey, username);
							boolean savePhone = Tools.savePreferences(
									MainPageActivty.this,
									Tools.sharePreferencesUserKey,
									Tools.UserPhonekey, phone);
							if (saveDataResult && saveUsername && savePhone) {
								createActionBarViewAndSlidingMenu();
								showUI();
							} else {
								ShowConnectErrorDialog(
										R.string.request_error_title,
										R.string.request_add_user_id_to_app_data);
							}

						}
					}
				});

			}
		}).start();
	}

	private void createActionBarViewAndSlidingMenu() {
		// Create Action Bar View
		actionBar = getSupportActionBar();

		// Create Sliding Menu View
		sildingLayout = (SlideHolder) findViewById(R.id.slideHolder);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.action_items, menu);
		return true;
	}

	private MenuItem menuItem;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		RelativeLayout left = (RelativeLayout) findViewById(R.id.left_sliding);
		RelativeLayout right = (RelativeLayout) findViewById(R.id.right_sliding);

		switch (item.getItemId()) {
		case R.id.menu_search:
			menuItem = item;
			Tools.Log(TAG, "Menu Search");
			if (!sildingLayout.isOpened()) {
				sildingLayout.setDirection(SlideHolder.DIRECTION_LEFT);
				right.setVisibility(View.GONE);
				left.setVisibility(View.VISIBLE);
				sildingLayout.toggle();
			} else {
				sildingLayout.toggle();
			}
			break;
		case R.id.menu_post:
			if (sildingLayout.isOpened())
				sildingLayout.toggle();

			menuItem = item;
			Tools.Log(TAG, "Menu Post");
			showChuyenMucDialog();

			break;
		case R.id.menu_mail:
			menuItem = item;
			Tools.Log(TAG, "Menu Mail");
			if (!sildingLayout.isOpened()) {
				sildingLayout.setDirection(SlideHolder.DIRECTION_RIGHT);
				right.setVisibility(View.VISIBLE);
				left.setVisibility(View.GONE);
				sildingLayout.toggle();
			} else
				sildingLayout.toggle();
			break;
		default:
			break;
		}
		return true;
	}

	private String city = "";
	private String topic = "";
	private LocationManager locationManager;
	private void showUI() {
		// Get a handle to the Map Fragment
		btn_search = (Button) findViewById(R.id.btn_left_sliding_search);
		txt_search = (EditText) findViewById(R.id.edit_left_sliding_search);
		spn_city_search = (Spinner) findViewById(R.id.spn_left_sliding_city);
		spn_topic_search = (Spinner) findViewById(R.id.spn_left_sliding_topic);
		btn_current_location = (ImageView) findViewById(R.id.btn_map_current_location);
		
		radioLangGroup = (RadioGroup) findViewById(R.id.radio_left_sliding_language);
		
		RadioButton rdoVi=(RadioButton) findViewById(R.id.rdo_left_sliding_language_vi);
		RadioButton rdoEn=(RadioButton) findViewById(R.id.rdo_left_sliding_language_en);
		
		String getLang=Tools.getLocaleString(MainPageActivty.this);
		if(getLang.equals("vi_VN"))
			rdoVi.setChecked(true);
		else
			rdoEn.setChecked(true);
		radioLangGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						int idRdo = group.getCheckedRadioButtonId();
						switch (idRdo) {
						case R.id.rdo_left_sliding_language_en:
							Tools.changeLang("en_US", MainPageActivty.this);
							break;
						case R.id.rdo_left_sliding_language_vi:
							Tools.changeLang("vi_VN", MainPageActivty.this);
							break;

						default:
							break;
						}
					}
				});
		spn_topic_search
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						city = arg0.getItemAtPosition(arg2).toString();
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}

				});
		spn_topic_search
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						topic = arg0.getItemAtPosition(arg2).toString();

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}

				});

		btn_search.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getDataFromTopicAndCityWithString(topic, city, txt_search
						.getText().toString().trim());
			}
		});
		
		btn_current_location.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
	                locationManager = (LocationManager) MainPageActivty.this.getSystemService(Context.LOCATION_SERVICE);
	                Criteria criteria = new Criteria();
	                String bestProvider = locationManager.getBestProvider(criteria, true);
	             
	                Location  location = locationManager.getLastKnownLocation(bestProvider);
	                if (location != null)
                    {
                        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                                new LatLng(location.getLatitude(), location.getLongitude()), 13));

                        CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                        .zoom(17)                   // Sets the zoom
                        .bearing(90)                // Sets the orientation of the camera to east
                        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                        .build();                   // Creates a CameraPosition from the builder
                    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                    }
	            } catch (java.lang.IllegalStateException ill) {
	                Toast.makeText(getBaseContext(),
	                        getString(R.string.request_error_title), Toast.LENGTH_SHORT)
	                        .show();
	            }
			}
		});

		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.fragment_detail_map)).getMap();
		//map.setMyLocationEnabled(true);
		LatLng defaultLocation = new LatLng(10.786857, 106.660924);

		map.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 18));

		map.setOnMapLongClickListener(this);
		map.setOnMarkerClickListener(this);
		// Marker melbourne = map.addMarker(new MarkerOptions()
		// .position(defaultLocation).title("Default Position")
		// .snippet("Welcome you using our App"));
		
		showChuyenMucDialog();
	}
	
	// Chuyen Muc items
	private String[] navChuyenMucTitles;
	private TypedArray navChuyenMucIcons;

	private void showChuyenMucDialog() {
		// Create Data for Chuyen Muc
		final ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();

		navChuyenMucTitles = getResources().getStringArray(
				R.array.array_chuyen_muc_items);

		// nav drawer icons from resources
		navChuyenMucIcons = getResources().obtainTypedArray(
				R.array.array_chuyen_muc_icons);

		for (int i = 0; i < navChuyenMucTitles.length; i++) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("name", navChuyenMucTitles[i]);
			data.put("img", navChuyenMucIcons.getResourceId(i, -1) + "");
			datas.add(data);
			Tools.Log(TAG, "add  data  : " + i);
		}

		Tools.Log(
				TAG,
				"Data  size : " + datas.size() + " : "
						+ navChuyenMucTitles.length + " : "
						+ navChuyenMucIcons.length());
		// Create Chuyen Muc View

		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.dialog_chuyen_muc);
		dialog.getWindow().setBackgroundDrawableResource(R.drawable.tranparent);
		ListView listView = (ListView) dialog
				.findViewById(R.id.list_chuyen_muc);
		ListChuyenMucAdapter adapter = new ListChuyenMucAdapter(this, datas);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// Chuyen Muc Click
				Tools.Log(TAG, "listView click item index : " + position);
				String topicString = navChuyenMucTitles[position];
				getDataFromTopicAndCityWithString(topicString, "", "");
				dialog.dismiss();

				/*
				 * switch (position) { case 0: // Chuyen muc 1
				 * 
				 * break; case 1: // Chuyen muc 2 break; case 2: // Chuyen muc 3
				 * break; case 3: // Chuyen muc 4 break; case 4: // Chuyen muc 5
				 * break; case 5: // Chuyen muc 6 break; case 6: // Chuyen muc 7
				 * break; case 7: // Chuyen muc 8 break; default: break; }
				 */
			}

		});

		dialog.setCancelable(true);
		dialog.setTitle(getString(R.string.topic_prompt));
		dialog.show();

		/*
		 * AlertDialog.Builder builder = new AlertDialog.Builder(this);
		 * builder.setTitle(null); builder.setView(dialoglayout);
		 * builder.setCancelable(true);
		 * 
		 * AlertDialog alertDialog = builder.create(); alertDialog.show();
		 */
	}

	public static ArrayList<News> data = new ArrayList<News>();

	private void getDataFromTopicAndCityWithString(final String topic,
			final String city, final String keysearch) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				data = newsController.getNewsForServer(topic, city);
				Tools.Log(TAG, "Data for marker : " + data.size());
				if (data.size() > 0) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							showMarkerToMap(keysearch);
						}
					});
				}
			}
		}).start();
	}

	private void showMarkerToMap(String keysearch) {

		map.clear();

		if (data != null && data.size() > 0) {

			for (int i = 0; i < data.size(); i++) {
				News value = data.get(i);
				LatLng location = new LatLng(value.getLati(), value.getLongti());
				if (keysearch.equals(""))
					map.addMarker(new MarkerOptions().position(location)
							.title(value.getTitle())
							.snippet(value.getCity().toString()));
				else {
					if (value.getTitle().contains(keysearch))
						map.addMarker(new MarkerOptions().position(location)
								.title(value.getTitle())
								.snippet(value.getCity().toString()));
				}
			}

		}
	}

	private void ShowConnectErrorDialog(int TitleID, int MsgID) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(TitleID);
		builder.setMessage(MsgID);
		builder.setCancelable(false);
		builder.setNegativeButton(getString(R.string.quit),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						MainPageActivty.this.finish();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	@Override
	public void onMapLongClick(LatLng point) {
		// TODO Auto-generated method stub
		double longti = point.longitude;
		double lati = point.latitude;
		// String city = "";
		// try {
		// Geocoder gcd = new Geocoder(MainPageActivty.this,
		// Locale.getDefault());
		// List<Address> addresses = gcd.getFromLocation(lati, longti, 1);
		// if (addresses.size() > 0)
		// city = addresses.get(0).getLocality();
		// } catch (Exception e) {
		// Tools.Log(TAG, "onMapLongClick error : " + e.toString());
		// }

		Intent intent_post = new Intent(MainPageActivty.this,
				PostActivity.class);
		intent_post.putExtra("longti", longti);
		intent_post.putExtra("lati", lati);
		startActivity(intent_post);

	}

	@Override
	public boolean onMarkerClick(Marker mark) {
		// usig getTitle of marker to catch the event !
		Intent intent_view = new Intent(MainPageActivty.this,
				ViewPostActivity.class);
		intent_view.putExtra("title", mark.getTitle());
		startActivity(intent_view);
		return false;
	}
}
